package cn.zvo.websocket.framework.springboot.util;

import java.util.List;
import com.xnx3.DateUtil;
import com.xnx3.json.JSONUtil;

import cn.zvo.websocket.framework.springboot.enums.MessageTypeEnum;
import cn.zvo.websocket.framework.springboot.vo.MessageReceiveVO;
import net.sf.json.JSONObject;

/**
 * 消息包装，将消息字符串格式化为指定格式
 * @author 管雷鸣
 *
 */
public class MessageUtil {
	
//	
//	/**
//	 * 加工，获取发送到socket客户端的消息字符串
//	 * @param sendId 发送者id,user.id ，如果用户未登录，是游客，这里可以是uuid
//	 * @param receiveId 接收者id,user.id ，如果用户未登录，是游客，这里可以是uuid
//	 * @param content 要发送的内容
//	 * @return 
//	 */
//	public static String send(MessageReceiveVO messageReceive){
//		//验证用户真实性，是否真的是这个用户发送的
////		User sendUser = UserUtil.getUser(messageReceive.getSendId());
//		return send(messageReceive.getType(), messageReceive.getSendId(), messageReceive.getReceiveId(), messageReceive.getText(), messageReceive.getExtend());
//	}
	

	/**
	 * 向客户端发送普通的MSG类型消息，也就是正常沟通的消息。
	 * @param sendId 发送者id,user.id ，如果用户未登录，是游客，这里可以是uuid
	 * @param receiveId 接收者id,user.id ，如果用户未登录，是游客，这里可以是uuid
	 * @param text 要发送的内容
	 */
	public static String sendMsgTypeMessage(String sendId, String receiveId, String text){
		MessageReceiveVO message = new MessageReceiveVO();
		message.setType(MessageTypeEnum.MSG.name);
		message.setReceiveId(receiveId);
		message.setSendId(sendId);
		message.setText(text);
		
		return JSONObject.fromObject(message).toString();
	}
	
	/**
	 * 将接收到的String格式的消息转化为JSON格式
	 * @param text 发送来的消息。格式如： {"token":"06e39913-cc11-4f01-a9cf-2b6c4a7853d6","data":{"mine":{"username":"纸飞机","avatar":"http://cdn.firstlinkapp.com/upload/2016_6/1465575923433_33812.jpg","id":"100000","mine":true,"content":"2323"},"to":{"username":"Lemon_CC","id":"102101","avatar":"http://tp2.sinaimg.cn/1833062053/180/5643591594/0","sign":"","name":"Lemon_CC","type":"friend"}}}
	 */
	public static MessageReceiveVO receiveStringToJson(String text){
		MessageReceiveVO msg = new MessageReceiveVO();
		JSONObject json = JSONObject.fromObject(text);
		String type = JSONUtil.getString(json, "type");
		msg.setType(type);
		
		//心跳,这种消息只会携带text参数
		if(type.equals(MessageTypeEnum.HEARTBEAT.name)){
			msg.setText(JSONUtil.getString(json, "text"));
			return msg;
		}
		
		//其他类型的消息，基本都会携带token
		if(json.get("token") != null){
//			msg.setBaseVO(MessageReceiveVO.FAILURE, "token为空");
//			return msg;
			msg.setToken(JSONUtil.getString(json, "token"));
		}
		msg.setToken(JSONUtil.getString(json, "token"));
		
		if(type.equals(MessageTypeEnum.MSG.name)){
			//正常的msg消息
			msg.setText(JSONUtil.getString(json, "text"));
			msg.setSendId(JSONUtil.getString(json, "sendId"));
			msg.setReceiveId(JSONUtil.getString(json, "receiveId"));
		}
		
		return msg;
	}
	
}
